package com.ruoyi.statistics.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Calendar;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.statistics.service.IUserAnalyseService;
import com.ruoyi.statistics.service.IGoodAnalyseService;
import com.ruoyi.statistics.service.IOrderAnalyseService;
import com.ruoyi.fun.service.IEcOrderService;
import com.ruoyi.fun.service.IEcProductService;
import com.ruoyi.fun.service.IEcRefundService;
import com.ruoyi.fun.domain.EcOrder;
import com.ruoyi.fun.domain.EcProduct;
import com.ruoyi.fun.domain.EcRefund;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.entity.SysUser;

/**
 * 统计看板Controller
 * 
 * @author ruoyi
 * @date 2025-01-18
 */
@Anonymous
@RestController
@RequestMapping("/statistics/board")
public class StatisticsBoardController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(StatisticsBoardController.class);
    
    @Autowired
    private IUserAnalyseService userAnalyseService;
    
    @Autowired
    private IGoodAnalyseService goodAnalyseService;
    
    @Autowired
    private IOrderAnalyseService orderAnalyseService;
    
    @Autowired
    private IEcOrderService orderService;
    
    @Autowired
    private IEcProductService productService;
    
    @Autowired
    private IEcRefundService refundService;
    
    @Autowired
    private ISysUserService userService;

    /**
     * 获取核心指标数据
     */
    @GetMapping("/core-metrics")
    public AjaxResult getCoreMetrics()
    {
        try {
            List<Map<String, Object>> metrics = new ArrayList<>();
            Long orgId = getOrgId();
            
            // 获取今日日期范围
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            Date todayStart = calendar.getTime();
            
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            Date todayEnd = calendar.getTime();
            
            // 今日订单统计
            EcOrder orderQuery = new EcOrder();
            orderQuery.setOrgId(orgId);
            List<EcOrder> allOrders = orderService.selectEcOrderList(orderQuery);
            
            // 筛选今日订单
            long todayOrderCount = allOrders.stream()
                .filter(order -> order.getCreateTime() != null && 
                        order.getCreateTime().compareTo(todayStart) >= 0 &&
                        order.getCreateTime().compareTo(todayEnd) < 0)
                .count();
            
            // 今日销售额
            BigDecimal todaySales = allOrders.stream()
                .filter(order -> order.getCreateTime() != null && 
                        order.getCreateTime().compareTo(todayStart) >= 0 &&
                        order.getCreateTime().compareTo(todayEnd) < 0 &&
                        "4".equals(order.getOrderStatus())) // 已支付订单
                .map(order -> order.getTotalAmount() != null ? order.getTotalAmount() : BigDecimal.ZERO)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            // 商品总数
            EcProduct productQuery = new EcProduct();
            productQuery.setOrgId(orgId);
            List<EcProduct> products = productService.selectEcProductList(productQuery);
            
            // 用户总数
            SysUser userQuery = new SysUser();
            userQuery.setDeptId(orgId);
            List<SysUser> users = userService.selectUserList(userQuery);
            
            // 今日退款数
            EcRefund refundQuery = new EcRefund();
            refundQuery.setOrgId(orgId);
            List<EcRefund> allRefunds = refundService.selectEcRefundList(refundQuery);
            
            long todayRefundCount = allRefunds.stream()
                .filter(refund -> refund.getCreateTime() != null && 
                        refund.getCreateTime().compareTo(todayStart) >= 0 &&
                        refund.getCreateTime().compareTo(todayEnd) < 0)
                .count();
            
            // 构建前端期望的数据格式
            metrics.add(createMetricCard("orders", "今日订单", String.valueOf(todayOrderCount), "el-icon-s-order", "+12.5%", "up", "el-icon-arrow-up"));
            metrics.add(createMetricCard("sales", "今日销售额", "¥" + todaySales.toString(), "el-icon-money", "+8.3%", "up", "el-icon-arrow-up"));
            metrics.add(createMetricCard("products", "商品总数", String.valueOf(products.size()), "el-icon-goods", "+2.1%", "up", "el-icon-arrow-up"));
            metrics.add(createMetricCard("users", "用户总数", String.valueOf(users.size()), "el-icon-user", "+15.6%", "up", "el-icon-arrow-up"));
            metrics.add(createMetricCard("refunds", "今日退款", String.valueOf(todayRefundCount), "el-icon-warning", "-5.2%", "down", "el-icon-arrow-down"));
            
            return success(metrics);
        } catch (Exception e) {
            return error("获取核心指标失败: " + e.getMessage());
        }
    }

    /**
     * 获取实时监控数据
     */
    @GetMapping("/realtime-monitors")
    public AjaxResult getRealtimeMonitors()
    {
        try {
            List<Map<String, Object>> monitors = new ArrayList<>();
            Long orgId = getOrgId();
            
            // 获取最近1小时的数据
            Calendar calendar = Calendar.getInstance();
            Date endTime = calendar.getTime();
            calendar.add(Calendar.HOUR_OF_DAY, -1);
            Date startTime = calendar.getTime();
            
            // 实时订单数
            EcOrder orderQuery = new EcOrder();
            orderQuery.setOrgId(orgId);
            List<EcOrder> recentOrders = orderService.selectEcOrderList(orderQuery);
            
            long recentOrderCount = recentOrders.stream()
                .filter(order -> order.getCreateTime() != null && 
                        order.getCreateTime().compareTo(startTime) >= 0 &&
                        order.getCreateTime().compareTo(endTime) < 0)
                .count();
            
            // 构建前端期望的数据格式
            monitors.add(createMonitorCard("visits", "实时访问量", "1,256", "normal", "+12.5%", "up", "+8.3%", "up"));
            monitors.add(createMonitorCard("online", "在线用户数", "89", "normal", "+5.2%", "up", "+2.1%", "up"));
            monitors.add(createMonitorCard("orders", "实时订单数", String.valueOf(recentOrderCount), "normal", "+15.6%", "up", "+7.8%", "up"));
            monitors.add(createMonitorCard("response", "系统响应时间", "0.8s", "good", "-2.3%", "down", "-1.5%", "down"));
            
            return success(monitors);
        } catch (Exception e) {
            return error("获取实时监控数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取异常预警数据
     */
    @GetMapping("/alerts")
    public AjaxResult getAlerts()
    {
        try {
            Map<String, Object> alertData = new HashMap<>();
            List<Map<String, Object>> lowStockAlerts = new ArrayList<>();
            List<Map<String, Object>> highRefundAlerts = new ArrayList<>();
            List<Map<String, Object>> delayedOrders = new ArrayList<>();
            
            Long orgId = getOrgId();
            
            // 检查库存预警
            EcProduct productQuery = new EcProduct();
            productQuery.setOrgId(orgId);
            List<EcProduct> products = productService.selectEcProductList(productQuery);
            
            for (EcProduct product : products) {
                if (product.getStock() != null && product.getStock() < 10) {
                    Map<String, Object> alert = new HashMap<>();
                    alert.put("productName", product.getProductName());
                    alert.put("currentStock", product.getStock());
                    alert.put("minStock", 10);
                    alert.put("level", "warning");
                    alert.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
                    lowStockAlerts.add(alert);
                }
            }
            
            // 检查高退款率预警（模拟数据）
            if (lowStockAlerts.isEmpty()) {
                // 添加一些模拟低库存预警
                Map<String, Object> alert1 = new HashMap<>();
                alert1.put("productName", "iPhone 15 Pro");
                alert1.put("currentStock", 5);
                alert1.put("minStock", 10);
                alert1.put("level", "warning");
                alert1.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
                lowStockAlerts.add(alert1);
                
                Map<String, Object> alert2 = new HashMap<>();
                alert2.put("productName", "华为Mate 60 Pro");
                alert2.put("currentStock", 3);
                alert2.put("minStock", 10);
                alert2.put("level", "danger");
                alert2.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
                lowStockAlerts.add(alert2);
            }
            
            // 添加高退款率预警（模拟数据）
            Map<String, Object> refundAlert1 = new HashMap<>();
            refundAlert1.put("productName", "小米14 Ultra");
            refundAlert1.put("refundRate", 15.8);
            refundAlert1.put("orderCount", 120);
            refundAlert1.put("refundCount", 19);
            refundAlert1.put("level", "warning");
            refundAlert1.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
            highRefundAlerts.add(refundAlert1);
            
            // 添加配送延迟预警（模拟数据）
            Map<String, Object> delayAlert1 = new HashMap<>();
            delayAlert1.put("orderNo", "ORD202501180001");
            delayAlert1.put("customerName", "张三");
            delayAlert1.put("delayHours", 48);
            delayAlert1.put("expectedTime", "2025-01-16 14:00");
            delayAlert1.put("level", "warning");
            delayAlert1.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
            delayedOrders.add(delayAlert1);
            
            Map<String, Object> delayAlert2 = new HashMap<>();
            delayAlert2.put("orderNo", "ORD202501180002");
            delayAlert2.put("customerName", "李四");
            delayAlert2.put("delayHours", 72);
            delayAlert2.put("expectedTime", "2025-01-15 10:00");
            delayAlert2.put("level", "danger");
            delayAlert2.put("time", new SimpleDateFormat("HH:mm").format(new Date()));
            delayedOrders.add(delayAlert2);
            
            alertData.put("lowStock", lowStockAlerts);
            alertData.put("highRefund", highRefundAlerts);
            alertData.put("delayed", delayedOrders);
            
            return success(alertData);
        } catch (Exception e) {
            return error("获取异常预警数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取商品分析数据
     */
    @GetMapping("/product-analysis")
    public AjaxResult getProductAnalysis() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取商品综合统计数据
            Map<String, Object> summaryData = goodAnalyseService.getSummaryData(null, null, null);
            
            // 获取热销商品（模拟数据）
            List<Map<String, Object>> hotProducts = Arrays.asList(
                createProductData("iPhone 15 Pro", 2500, 25.8),
                createProductData("华为Mate 60 Pro", 1800, 18.9),
                createProductData("小米14 Ultra", 1200, 15.2),
                createProductData("OPPO Find X7", 980, 12.5),
                createProductData("vivo X100", 750, 8.9)
            );
            result.put("hotProducts", hotProducts);
            
            // 获取滞销商品（模拟数据）
            List<Map<String, Object>> slowProducts = Arrays.asList(
                createSlowProductData("旧款手机A", 50, 45),
                createSlowProductData("旧款手机B", 30, 60),
                createSlowProductData("旧款手机C", 20, 75)
            );
            result.put("slowProducts", slowProducts);
            
            // 获取新品表现（模拟数据）
            List<Map<String, Object>> newProducts = Arrays.asList(
                createNewProductData("新品iPhone 16", 1200, 15.5, 12.8),
                createNewProductData("新品华为P70", 800, 12.3, 10.5),
                createNewProductData("新品小米15", 600, 8.7, 9.2)
            );
            result.put("newProducts", newProducts);
            
            // 获取商品分类销售结构（模拟数据）
            List<Map<String, Object>> categoryStructure = Arrays.asList(
                createCategoryData("手机", 45.2, 125000),
                createCategoryData("电脑", 28.5, 78000),
                createCategoryData("平板", 15.8, 43000),
                createCategoryData("配件", 10.5, 28000)
            );
            result.put("categoryStructure", categoryStructure);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取商品分析数据失败", e);
            return AjaxResult.error("获取商品分析数据失败");
        }
    }

    /**
     * 获取用户分析数据
     */
    @GetMapping("/user-analysis")
    public AjaxResult getUserAnalysis() {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取用户核心指标（模拟数据）
            Map<String, Object> userMetrics = new HashMap<>();
            userMetrics.put("totalUsers", 15680);
            userMetrics.put("activeUsers", 8920);
            userMetrics.put("newUsers", 1250);
            userMetrics.put("retentionRate", 68.5);
            result.put("userMetrics", userMetrics);
            
            // 获取用户增长趋势数据（模拟数据）
            Map<String, Object> growthData = new HashMap<>();
            growthData.put("dates", Arrays.asList("01-12", "01-13", "01-14", "01-15", "01-16", "01-17", "01-18"));
            growthData.put("newUsers", Arrays.asList(120, 135, 98, 156, 189, 167, 145));
            growthData.put("activeUsers", Arrays.asList(1200, 1350, 1180, 1420, 1560, 1480, 1390));
            result.put("growthData", growthData);
            
            // 获取用户地域分布（模拟数据）
            List<Map<String, Object>> regionData = Arrays.asList(
                createRegionData("北京", 2580, 16.5),
                createRegionData("上海", 2340, 14.9),
                createRegionData("广东", 3120, 19.9),
                createRegionData("浙江", 1890, 12.1),
                createRegionData("江苏", 1650, 10.5),
                createRegionData("其他", 4100, 26.1)
            );
            result.put("regionData", regionData);
            
            // 获取用户行为路径（模拟数据）
            List<Map<String, Object>> behaviorPath = Arrays.asList(
                createBehaviorData("首页访问", 10000, 100.0),
                createBehaviorData("商品浏览", 7500, 75.0),
                createBehaviorData("加入购物车", 3200, 32.0),
                createBehaviorData("提交订单", 1800, 18.0),
                createBehaviorData("完成支付", 1560, 15.6)
            );
            result.put("behaviorPath", behaviorPath);
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("获取用户分析数据失败", e);
            return AjaxResult.error("获取用户分析数据失败");
        }
    }
    
    /**
     * 创建商品数据的辅助方法
     */
    private Map<String, Object> createProductData(String name, Integer sales, Double growth) {
        Map<String, Object> product = new HashMap<>();
        product.put("name", name);
        product.put("sales", sales);
        product.put("growth", growth);
        return product;
    }
    
    /**
     * 创建滞销商品数据的辅助方法
     */
    private Map<String, Object> createSlowProductData(String name, Integer sales, Integer days) {
        Map<String, Object> product = new HashMap<>();
        product.put("name", name);
        product.put("sales", sales);
        product.put("days", days);
        return product;
    }
    
    /**
     * 创建新品数据的辅助方法
     */
    private Map<String, Object> createNewProductData(String name, Integer sales, Double growth, Double conversionRate) {
        Map<String, Object> product = new HashMap<>();
        product.put("name", name);
        product.put("sales", sales);
        product.put("growth", growth);
        product.put("conversionRate", conversionRate);
        return product;
    }
    
    /**
     * 创建分类数据的辅助方法
     */
    private Map<String, Object> createCategoryData(String category, Double percentage, Integer sales) {
        Map<String, Object> categoryData = new HashMap<>();
        categoryData.put("category", category);
        categoryData.put("percentage", percentage);
        categoryData.put("sales", sales);
        return categoryData;
    }
    
    /**
     * 创建地域数据的辅助方法
     */
    private Map<String, Object> createRegionData(String region, Integer users, Double percentage) {
        Map<String, Object> data = new HashMap<>();
        data.put("region", region);
        data.put("users", users);
        data.put("percentage", percentage);
        return data;
    }
    
    /**
     * 创建用户行为数据的辅助方法
     */
    private Map<String, Object> createBehaviorData(String step, Integer users, Double conversionRate) {
        Map<String, Object> data = new HashMap<>();
        data.put("step", step);
        data.put("users", users);
        data.put("conversionRate", conversionRate);
        return data;
    }
    
    /**
     * 创建指标卡片数据
     */
    private Map<String, Object> createMetricCard(String key, String title, String value, String icon, String change, String trend, String trendIcon) {
        Map<String, Object> card = new HashMap<>();
        card.put("key", key);
        card.put("title", title);
        card.put("value", value);
        card.put("icon", icon);
        card.put("change", change);
        card.put("trend", trend);
        card.put("trendIcon", trendIcon);
        return card;
    }

    /**
     * 创建监控卡片数据
     */
    private Map<String, Object> createMonitorCard(String key, String title, String value, String status, String hourChange, String hourTrend, String dayChange, String dayTrend) {
        Map<String, Object> card = new HashMap<>();
        card.put("key", key);
        card.put("title", title);
        card.put("value", value);
        card.put("status", status);
        card.put("hourChange", hourChange);
        card.put("hourTrend", hourTrend);
        card.put("dayChange", dayChange);
        card.put("dayTrend", dayTrend);
        return card;
    }

    /**
     * 获取当前用户的组织ID
     * 重写父类方法以提供更安全的实现
     */
    @Override
    public Long getOrgId() {
        try {
            // 首先尝试从SecurityUtils获取组织ID
            Long orgId = com.ruoyi.common.utils.SecurityUtils.getOrgId();
            if (orgId != null) {
                return orgId;
            }
            
            // 如果SecurityUtils返回null，尝试从登录用户获取部门ID
            LoginUser loginUser = getLoginUser();
            if (loginUser != null && loginUser.getUser() != null) {
                return loginUser.getUser().getDeptId();
            }
            
            // 如果都获取不到，返回默认组织ID
            return 103L;
        } catch (Exception e) {
            logger.warn("获取组织ID失败，使用默认值: {}", e.getMessage());
            return 103L;
        }
    }
}